<?php


namespace app\common\service\finance\merchant;


use app\model\Agent;
use app\model\AgentBalanceLog;
use app\model\AgentMerchantStat;
use app\model\AgentMerchantStatItem;
use Carbon\Carbon;
use think\facade\Log;

/**
 * 统计
 * Class StatBalanceService
 * @package app\common\service\finance\merchant
 */
class BalanceService
{

    private $log;


    public function handle()
    {
        //传入商户id

    }

    /**
     * 根据有商户id 处理统计数据
     */
    public function statByMerchantId($merchant_id)
    {

        /**
         * 处理时间转化
         */
        $this->handleStat();

        //查询余额记录表数据
        $datas = $this->statAgentByAgentIDAndMerChantId($merchant_id);

        $total_amount = 0;
        $temp = [];

        /**
         * @var AgentBalanceLog $obj
         */
//        [{"amount":"9979650","agent_id":12,"date":"2021-09"},{"amount":"-4550","agent_id":13,"date":"2021-09"},{"amount":"-4550","agent_id":12,"date":"2021-08"}]

        foreach ($datas as $obj) {
            $total_amount += $obj->amount;
            $temp[$obj->date][] = $obj;
        }

//        {"2021-09":[{"amount":"9979650","agent_id":12,"date":"2021-09"},{"amount":"-4550","agent_id":13,"date":"2021-09"}],"2021-08":[{"amount":"-4550","agent_id":12,"date":"2021-08"}]}

        foreach ($temp as $date => $objs) {

            $date = Carbon::parse($date)->format('Y-m-d');

            $agentMerchantStat = AgentMerchantStat::findOrCreate([
                'merchant_id' => $merchant_id,
                'settle_at' => $date,
                'status' => 0,
            ]);


            foreach ($objs as $obj) {

                $agentMerchantStatItem = AgentMerchantStatItem::findOrNew([
                    'agent_id' => $obj->agent_id,
                    'settle_at' => $date,
                    'merchant_id' => $merchant_id,
                    'agent_merchant_stat_id' => $agentMerchantStat->id,
                    'app_id' => !empty($obj->agent) ? $obj->agent->app_id : 0,
                ]);

                $agentMerchantStatItem->amount += $obj->amount;
                $agentMerchantStatItem->save();

                $agentMerchantStat->amount += $obj->amount;
            }

            $agentMerchantStat->save();

        }

        Log::info($this->log);
    }


    /**
     * @param $merchant_id
     * @return Agent[]|array|\think\Collection|Agent
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAgnetIdsByMerchantId($merchant_id)
    {

        $this->log[] = '处理商户id为：' . $merchant_id . PHP_EOL;

        return Agent::where('merchant_id', $merchant_id)
            ->where('is_deleted', Agent::IS_DELETE_FALSE)
            ->column('id');
    }

    /**
     * @param $agent_id
     */
    public function statAgentByAgentIDAndMerChantId($merchant_id)
    {


        $startAt = Carbon::now()->subYears(50);
        $endAt = Carbon::now()->startOfMonth();

        $this->log[] = '查询区间为：' . $startAt . '~' . $endAt . PHP_EOL;

        //获取所有的代理id
        $agentIds = $this->getAgnetIdsByMerchantId($merchant_id);

        $query = AgentBalanceLog::query()
            ->whereBetweenTime('stat_at', $startAt, $endAt)
            ->whereIn('type', AgentBalanceLog::commission())
            ->where('stat_status', AgentBalanceLog::STAT_STATUS_WAIt)
            ->where('created_at','<','2023-02-25 01:00:00')
            ->whereIn('agent_id', $agentIds);

        $selectQuery = clone $query;

        $balances = $query
            ->field("sum(amount) as amount,agent_id, date_format(stat_at,'%Y-%m') as date")
            ->group('date,agent_id')
            ->select();

        //把这些统计全部改为已统计
        $selectQuery->select()->each(function (AgentBalanceLog $agentBalanceLog) {
            $agentBalanceLog->stat_status = AgentBalanceLog::STAT_STATUS_STAT;
            $agentBalanceLog->save();
        });


        $this->log[] = '查找到数据为：' . json_encode($balances);

        return $balances;
    }

    /**
     * 最近的统计时间，如果没有则返回空
     * @param $merchant_id
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recentRecodeSettleAtByMerchantId($merchant_id)
    {

        $obj = AgentMerchantStat::where('merchant_id', $merchant_id)
            ->order('settle_at', 'desc')->find();

        $settleAt = !empty($obj) ? $obj->settle_at : '';

        $this->log[] = '获取该商户的最近结算的时间：' . $settleAt . PHP_EOL;

        return $settleAt;

    }


    /**
     * 处理结算的时间
     */
    public function handleStat()
    {

        AgentBalanceLog::query()
            ->leftJoin('agent', 'agent.id = agent_balance_log.agent_id')
            ->where('agent_balance_log.stat_at', null)
            ->where('agent.is_relation', 1)
            ->field('agent_balance_log.*')
            ->select()->each(function (AgentBalanceLog $agentBalanceLog) {
                $agentBalanceLog->stat_at = Carbon::parse($agentBalanceLog->created_at)->subMonth()->startOfMonth()->addSecond()->format('Y-m-d');
                $agentBalanceLog->save();
            });


    }


}